/*
 * Copyright (C) 2018 Logos Technology Ltd.
 */

package com.logos.common.source.network.converter;

import com.logos.common.source.network.entity.BaseNetEntity;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.reflect.TypeToken;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

/**
 * @author Young Ken
 */
@SuppressWarnings("all")
public class CustomGsonConverterFactory extends Converter.Factory {

    private final Gson mGson;

    private CustomGsonConverterFactory(Gson gson) {
        if (gson == null) {
            throw new NullPointerException("gson must not null");
        }
        mGson = gson;
    }

    /**
     * create {@linkplain CustomGsonConverterFactory}
     *
     * @return {@linkplain CustomGsonConverterFactory}
     */
    public static CustomGsonConverterFactory create() {
        return create(new Gson());
    }

    /**
     * create {@linkplain CustomGsonConverterFactory}
     *
     * @param gson gson
     * @return create {@linkplain CustomGsonConverterFactory}
     */
    public static CustomGsonConverterFactory create(Gson gson) {
        return new CustomGsonConverterFactory(gson);
    }

    @Override
    public Converter<?, RequestBody> requestBodyConverter(Type type,
                                                          Annotation[] parameterAnnotations,
                                                          Annotation[] methodAnnotations,
                                                          Retrofit retrofit) {
        TypeAdapter<?> adapter = mGson.getAdapter(TypeToken.get(type));
        return new CustomGsonRequestBodyConverter<>(mGson, adapter);
    }

    @Override
    public Converter<ResponseBody, ?> responseBodyConverter(Type type,
                                                            Annotation[] annotations,
                                                            Retrofit retrofit) {
        TypeAdapter<?> adapter = mGson.getAdapter(TypeToken.get(type));
        return new CustomGsonResponseBodyConverter<BaseNetEntity<?>>(mGson,
                (TypeAdapter<BaseNetEntity<?>>) adapter);
    }
}
